package com.yzt.zhuju.download;

import android.os.Environment;
import android.text.TextUtils;

import com.yzt.zhuju.config.AppConfig;
import com.yzt.p_base.utils.FileUtils;
import com.yzt.p_base.utils.LogDataUtils;

import java.io.File;

import rx.Subscriber;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   :
 */
public class FileCacheManager {

    private final String TAG = "FileCacheManager";

    public static final String PATH_GIFT_ANIM_DOWNLOAD = getFileRootPath() + File.separator + "giftFile";
    public static final String PATH_IMAGE_DOWNLOAD = getFileRootPath() + File.separator + "imageFile";
    public static final String PATH_MUSIC_DOWNLOAD = getFileRootPath() + File.separator + "musicFile";
    public static final String PATH_JSON_DOWNLOAD = getFileRootPath() + File.separator + "json";
    public static final String PATH_APK_DOWNLOAD = getFileRootPath() + File.separator + "apk";

    private static String getFileRootPath() {
        File fileRootDir = AppConfig.application.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        if (fileRootDir != null) {
            return fileRootDir.getAbsolutePath() + File.separator;
        } else {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
        }
    }

    private static FileCacheManager mInstance;

    public static FileCacheManager getInstance() {
        if (mInstance == null) {
            synchronized (FileCacheManager.class) {
                if (mInstance == null) {
                    mInstance = new FileCacheManager();
                }
            }
        }
        return mInstance;
    }

    public long getFileSize() {
        long animSize = FileUtils.getFolderSize(new File(FileCacheManager.PATH_GIFT_ANIM_DOWNLOAD));
        long imageSize = FileUtils.getFolderSize(new File(FileCacheManager.PATH_IMAGE_DOWNLOAD));
        long musicSize = FileUtils.getFolderSize(new File(FileCacheManager.PATH_MUSIC_DOWNLOAD));
        long jsonSize = FileUtils.getFolderSize(new File(FileCacheManager.PATH_JSON_DOWNLOAD));
        return animSize + imageSize + musicSize + jsonSize;
    }

    public void deleteCacheFile() {
        FileUtils.deleteFolderFile(FileCacheManager.PATH_GIFT_ANIM_DOWNLOAD, true);
        FileUtils.deleteFolderFile(FileCacheManager.PATH_IMAGE_DOWNLOAD, true);
        FileUtils.deleteFolderFile(FileCacheManager.PATH_MUSIC_DOWNLOAD, true);
        FileUtils.deleteFolderFile(FileCacheManager.PATH_APK_DOWNLOAD, true);
    }

    public void deleteApkCacheFile() {
        FileUtils.deleteFolderFile(FileCacheManager.PATH_APK_DOWNLOAD, true);
    }

    public void getDomainFileUrl(String fileUrl, OnCallBackFileUrlListener listener) {
        getFileUrl(true, PATH_JSON_DOWNLOAD, fileUrl, listener);
    }

    public void fileIsExists(String fileDirs, String fileUrl, OnCallBackFileIsExistsListener listener) {
        if (TextUtils.isEmpty(fileUrl)) {
            if (listener != null) {
                listener.fileNotExists(fileUrl, new Exception("文件不存在"));
            }
            return;
        }
        if (!fileUrl.contains("http")) {
            if (listener != null) {
                listener.fileNotExists(fileUrl, new Exception("文件不存在"));
            }
            return;
        }
        LogDataUtils.d(TAG, "fileUrl:\t" + fileUrl);
        File dir = new File(fileDirs);
        if (!dir.exists()) {
            dir.mkdirs();
            LogDataUtils.d(TAG, "!dir.exists()");
        }
        String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        LogDataUtils.d(TAG, "fileName:" + fileName);
        File file = new File(fileDirs + "/" + fileName);
        if (file.exists()) {
            LogDataUtils.d(TAG, "file.exists():" + file.getAbsolutePath());
            if (listener != null) {
                listener.fileExists(file.getAbsolutePath());
            }
        } else {
            if (listener != null) {
                listener.fileNotExists(fileUrl, new Exception("文件不存在"));
            }
        }
    }

    public void getFileUrl(boolean reLoad, String fileDirs, String fileUrl, OnCallBackFileUrlListener listener) {
        if (TextUtils.isEmpty(fileUrl)) {
            if (listener != null) {
                listener.getFileUrl("");
            }
            return;
        }
        if (!fileUrl.contains("http")) {
            if (listener != null) {
                listener.getFileUrl(fileUrl);
            }
            return;
        }
        LogDataUtils.d(TAG, "fileUrl:\t" + fileUrl);
        File dir = new File(fileDirs);
        if (!dir.exists()) {
            dir.mkdirs();
            LogDataUtils.d(TAG, "!dir.exists()");
        }
        String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        LogDataUtils.d(TAG, "fileName:" + fileName);
        File file = new File(fileDirs + "/" + fileName);
        if (!reLoad) {
            if (file.exists()) {
                LogDataUtils.d(TAG, "file.exists():" + file.getAbsolutePath());
                if (listener != null) {
                    listener.getFileUrl(file.getAbsolutePath());
                }
                return;
            }
            loadFile(fileUrl, file, listener);
        } else {
            loadFile(fileUrl, file, listener);
        }
    }

    private void loadFile(String fileUrl, File file, OnCallBackFileUrlListener listener) {
        DownloadUtils downloadUtils = new DownloadUtils(new ProgressListener() {
            @Override
            public void onStartDownload(long length) {
                LogDataUtils.d(TAG, "onStartDownload:" + length);
                LogDataUtils.d("download_apk_onStartDownload", "" + length);
                listener.onProgressLength(length);
            }

            @Override
            public void onProgress(int progress) {
                LogDataUtils.d(TAG, "onProgress:" + progress);
                LogDataUtils.d("download_apk_onProgress", "" + progress);
                listener.onProgress(progress);
            }

            @Override
            public void onFail(String errorInfo) {
                LogDataUtils.d(TAG, "onFail:" + errorInfo);
            }
        });

        downloadUtils.download(fileUrl, file, new Subscriber() {
            @Override
            public void onCompleted() {
                LogDataUtils.d("download_apk_onCompleted", "");
                LogDataUtils.d(TAG, "onCompleted:" + fileUrl + "\t\t\t" + file.getAbsolutePath());
                listener.getFileUrl(file.getAbsolutePath());
            }

            @Override
            public void onError(Throwable e) {
                LogDataUtils.d("download_apk_onError", "");
                LogDataUtils.d(TAG, "onError:" + e.toString());
                listener.loadFileFail(fileUrl, e);
            }

            @Override
            public void onNext(Object o) {
                LogDataUtils.d("download_apk_onNext", "");
            }
        });
    }

    public interface OnCallBackFileUrlListener {

        void getFileUrl(String fileUrl);

        void onProgressLength(long length);

        void onProgress(int progress);

        void loadFileFail(String fileUrl, Throwable e);
    }

    public interface OnCallBackFileIsExistsListener {

        void fileExists(String fileUrl);

        void fileNotExists(String fileUrl, Throwable e);
    }

}
